import App, {Container} from 'next/app'
import {Provider} from 'react-redux'
import {withRouter} from 'next/router' // 接入next的router
import Router from 'next/router'
import NProgress from 'nprogress'
import withReduxStore from '../lib/with-redux-store'
import * as API from '../api/api'
import {getJwt} from '../lib/auth'
import {updateInfo} from '../store/user/action'
import '../styles/styles.less'
class MyApp extends App {
    constructor(props) {
        super(props);
        this.state = {
            userAgent:'',
        }

    }
    static async getInitialProps ({ Component, router, ctx}) {
        let {reduxStore,req} = ctx;
        let {dispatch} = reduxStore;
        let pageProps = {}
        let token = getJwt({req});
        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx)
        }
        if(token&&!!req){
            let res = await API.getUserInfo({token})
            if (res.data.code === 1) {
                let {username,avatar,_id} = res.data.data;
                dispatch(updateInfo({
                    avatar,
                    username,
                    userId:_id
                }))
            }
        }
       
        return { pageProps }
    }
    
    async componentDidMount() {
        // let {reduxStore} = this.props
        // let res = await API.getUserInfo()
        // if (res.data.code === 1) {
        //     let {username,avatar,email} = res.data.data;
        //     reduxStore.dispatch({
        //         type: 'SET_USERNAME',
        //         username
        //     })
        //     reduxStore.dispatch({
        //         type: 'SET_AVATAR',
        //         avatar
        //     })
          
        // }
        // console.log(reduxStore.getState().user)
    //     const ua = navigator.userAgent;
    //     let userAgent;
    //     if (ua.indexOf("Android") > 0 || ua.indexOf("iPhone") > 0 || ua.indexOf("iPad") > 0) {
    //         //移动端
    //         userAgent = 'mobile'
    //     } else {
    //       userAgent = 'pc'
    //     }
    
    //   console.log(userAgent)
    }
    render(){
        Router.onRouteChangeStart = (url) => {
            NProgress.start()
        }
        Router.onRouteChangeComplete = () => NProgress.done()
        Router.onRouteChangeError = () => NProgress.done()
        const {Component, pageProps, reduxStore} = this.props;
        return (
            <Container>
                <Provider store={reduxStore}>
                    <div>
                      <Component {...pageProps}  />
                    </div>
                </Provider>
            </Container>
        )
    }


}

export default withReduxStore(withRouter(MyApp))